<template>
  <div class="titan-translate-item">
    {{ text }}

    <span
      v-if="max > 0 && max < text.length"
      @click.stop="isCollapsed = !isCollapsed"
      class="titan-translate-item_text"
    >
      {{ !isCollapsed ? "收起" : "查看更多" }}
    </span>

    <template v-if="!loading && text.length">
      <span
        v-if="mode !== 3"
        @click.stop="handleTranslateChange"
        class="titan-translate-item_text"
      >
        {{ translatedVisible ? "显示原文" : "翻译" }}
      </span>
    </template>
    <slot />
  </div>
</template>

<script setup lang="ts">
  import { ITranslateItem } from "@/components/translate/src/types";
  import { computed, ref, watch } from "vue";

  defineOptions({
    name: "TitanTranslateItem",
  });

  const emit = defineEmits(["translate"]);

  const props = withDefaults(defineProps<ITranslateItem>(), {
    content: "",
    translateContent: "",
    max: 0,
    loading: false,
    mode: 1, // 1 优先译文 2 优先原文 3 原文 + 译文
    isOrigin: false,
  });

  const isCollapsed = ref(true);
  const translatedVisible = ref(false);

  watch(
    () => props.isOrigin,
    (value) => {
      translatedVisible.value = !value;
    },
    { immediate: true }
  );

  const text = computed((): any => {
    const _text: string = !translatedVisible.value ? props.content : props.translateContent;
    return isCollapsed.value ? (props.max && _text.length > props.max ? _text.slice(0, props.max) + "..." : _text) : _text;
  });

  const handleTranslateChange = () => {
    translatedVisible.value = !translatedVisible.value;
    if (!props.translateContent) {
      emit("translate");
    }
  };
</script>
